package com.office.automate.dataaccess.impl.user;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;

import com.office.automate.dataaccess.def.user.SystemLoginAuthenticationDao;
import com.office.automate.dataaccess.framework.DataAccessSessionFactory;
import com.office.automate.exception.authenticate.UserAuthenticationExcaptionKeys;
import com.office.automate.exception.employee.EmployeeExceptionKeys;
import com.office.automate.exception.framework.FrontierVisibleException;
import com.office.automate.model.authenticate.ChangePassword;
import com.office.automate.model.authenticate.UserAuthenticator;
import com.office.automate.model.employee.Employee;

public class SystemLoginAuthenticationDaoImplementer implements SystemLoginAuthenticationDao {
	private static SessionFactory sessionFactory = null;

	static {
		sessionFactory = DataAccessSessionFactory.getSessionFactory();
	}

	public UserAuthenticator getAuthenticationDetailsByUsername(String anUsername) throws FrontierVisibleException {

		Session  session = null;
		UserAuthenticator authenticator = null;
		try {
			session = getSessionFactory().openSession();
			Criteria criteria = session.createCriteria(Employee.class);
			criteria.add(Restrictions.eq("username", anUsername));
			criteria.setMaxResults(1);
			Employee employee = (Employee) criteria.uniqueResult();
			if (employee != null) {
				authenticator = new UserAuthenticator();
				authenticator.setEmployeeId(employee.getEmployeeId());
				authenticator.setUsername(employee.getUsername());
				authenticator.setPassword(employee.getPassword());
				authenticator.setFirstName(employee.getFirstName());
				authenticator.setLastName(employee.getLastName());
				authenticator.setSecurityLevels(employee.getSecurityLevel());
			} else {
				throw new FrontierVisibleException(UserAuthenticationExcaptionKeys.USERNAME_OR_PASSWORD_INCORRECT, null);
			}
		} catch(Exception e) {
			throw new FrontierVisibleException(UserAuthenticationExcaptionKeys.USERNAME_OR_PASSWORD_INCORRECT, e);
		} finally {
			session.flush();
			session.close();
		}
		return authenticator;
	}

	public static SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	public void changePassword(ChangePassword changePassword) throws FrontierVisibleException {
		Session  session = null;
		try {
			session = getSessionFactory().openSession();
			Employee employee = new EmployeeDaoImplementer().getEmployeeDetails(changePassword.getEmployeeId());
			employee.setPassword(changePassword.getNewPassword());
			session.beginTransaction();   
			session.update(employee);
			session.getTransaction().commit();  
		} catch(Exception e) {
			throw new FrontierVisibleException(EmployeeExceptionKeys.ERROR_OCCORRED_DURING_UPDATING_EMPLOYEE_DETAILS, e);
		} finally {
			session.flush();
			session.close();
		}
	}
}